package com.ufo.store.management.ui.activity;

import android.app.SharedElementCallback;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.UrlSafeBase64;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.entity.Isszmbalv3Member;
import com.ufo.store.management.entity.QiniuControl;
import com.ufo.store.management.entity.ServiceResult;
import com.ufo.store.management.net.NetCallback;
import com.ufo.store.management.net.NetHelper;
import com.ufo.store.management.ui.fragment.Isszmbalv3MemberEditFragment;
import com.ufo.store.management.utils.Auth;
import com.ufo.store.management.utils.GlideUtils;
import com.ufo.store.management.utils.PhotoUtils;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.dialog.PickImageDialog;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ufo.store.management.BarApplication.mSavePictureDirPath;

/**
 * Created by taoli on 2017/12/29.
 */

public class Isszmbalv3MemberEditActivity extends BaseActivity {
    // View name of the header image. Used for activity scene transitions
    public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";

    // View name of the header title. Used for activity scene transitions
    public static final String VIEW_NAME_HEADER_TITLE = "detail:header:title";

    private AppBarLayout appBarLayout;
    private Toolbar toolBar;
    private CollapsingToolbarLayout coordinatorLayout;

    private ImageView mMemberIconIv = null;

    private Isszmbalv3MemberEditFragment mIsszmbalv3MemberEditFragment = null;

    //传入参数
    private Isszmbalv3Member mIsszmbalv3MemberInfo = null;
    private boolean mbIsInsertData = true;

    private Configuration qiniuConfig;

    private PickImageDialog mPickImageDialog = null;
    private String mPicDescPath = null;
    private PhotoUtils mPhotoUtils;

    private boolean mIsReturning = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    /**
     * Schedules the shared element transition to be started immediately
     * after the shared element has been measured and laid out within the
     * activity's view hierarchy. Some common places where it might make
     * sense to call this method are:
     *
     * (1) Inside a Fragment's onCreateView() method (if the shared element
     *     lives inside a Fragment hosted by the called Activity).
     *
     * (2) Inside a Picasso Callback object (if you need to wait for Picasso to
     *     asynchronously load/scale a bitmap before the transition can begin).
     *
     * (3) Inside a LoaderCallback's onLoadFinished() method (if the shared
     *     element depends on data queried by a Loader).
     */
    private void scheduleStartPostponedTransition(final View sharedElement) {
        sharedElement.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        sharedElement.getViewTreeObserver().removeOnPreDrawListener(this);
                        startPostponedEnterTransition();
                        return true;
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if(state == 0){
            getMenuInflater().inflate(R.menu.stockedit_dark_menu, menu);
        }else if(state == 1 ){
            getMenuInflater().inflate(R.menu.stockedit_light_menu, menu);
        }
        return true;
    }

    private Toolbar.OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_save:
                    if (mIsszmbalv3MemberEditFragment != null)
                        mIsszmbalv3MemberEditFragment.submitIsszmbalv3MemberEdit();
                    break;
                case R.id.action_queue:
                    pickPicDescImage();
                    break;
            }
            return true;
        }
    };

    @Override
    public void finishAfterTransition() {
        mIsReturning = true;
        super.finishAfterTransition();
    }
    
    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mIsszmbalv3MemberInfo = (Isszmbalv3Member) bundle.getSerializable("Isszmbalv3MemberInfo");
                if (mIsszmbalv3MemberInfo != null)
                    mbIsInsertData = false;
                else
                    mIsszmbalv3MemberInfo = new Isszmbalv3Member();
            }
        }
        qiniuConfig = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        mPhotoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(Uri uri) {
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    mPicDescPath = Utils.getPath(Isszmbalv3MemberEditActivity.this, uri);
                    if (!TextUtils.isEmpty(mPicDescPath)) {
                        GlideUtils.LoadImageWithLocation(getActivity(), mPicDescPath, mMemberIconIv );
                    }
                }
            }
            @Override
            public void onPhotoCancel() {
            }
        });
    }

    private void initView() {
        setContentView(R.layout.activity_isszambalv3_member_edit);
        postponeEnterTransition();
        StatusBarUtil.StatusBarLightMode(Isszmbalv3MemberEditActivity.this, R.color.transparent, false);
        toolBar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolBar);
        toolBar.setNavigationIcon(R.drawable.ic_back_selector);
        toolBar.setOnMenuItemClickListener(onMenuItemClickListener);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAfterTransition();
            }
        });
        this.setEnterSharedElementCallback(new SharedElementCallback() {
            @Override
            public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
                if (mIsReturning) {
                    //折叠状态清楚共享动画
                    if (state == 1) {
                        // If shared element is null, then it has been scrolled off screen and
                        // no longer visible. In this case we cancel the shared element transition by
                        // removing the shared element from the shared elements map.
                        names.clear();
                        sharedElements.clear();
                    }
                }
                super.onMapSharedElements(names, sharedElements);
            }

            @Override
            public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
                super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
                if( mIsReturning ){
                    //toolBar.setVisibility(View.INVISIBLE);
                }else{
                    //toolBar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
                super.onSharedElementStart(sharedElementNames,sharedElements,sharedElementSnapshots);
            }

            @Override
            public void onSharedElementsArrived(List<String> sharedElementNames, List<View> sharedElements, SharedElementCallback.OnSharedElementsReadyListener listener) {
                super.onSharedElementsArrived(sharedElementNames,sharedElements,listener);
            }
        });
        coordinatorLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
        appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);

        mMemberIconIv = (ImageView) findViewById(R.id.member_icon_iv);
        mMemberIconIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                ArrayList list = new ArrayList();
                ArrayList<String> imgUrlList = new ArrayList<>();
                ArrayList<String> imgDescriptionList = new ArrayList<>();
                if (mIsszmbalv3MemberInfo != null && !TextUtils.isEmpty(mIsszmbalv3MemberInfo.memberName)) {
                    //imgUrlList.add(BarApplication.Qiniu_BaseDownloadHost + BarApplication.mStoreName + "_" + "memberId_" + mIsszmbalv3MemberInfo.memberCardNo + ".jpg");
                    imgUrlList.add("file://" + mSavePictureDirPath + BarApplication.mStoreName + "_" + "memberId_" + mIsszmbalv3MemberInfo.memberCardNo  + ".jpg");
                    imgDescriptionList.add(mIsszmbalv3MemberInfo.memberName);
                }
                list.add(imgUrlList);
                list.add(imgDescriptionList);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("list", list);
                bundle.putInt("pos", 0);
                intent.setClass(Isszmbalv3MemberEditActivity.this, PictureViewActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        scheduleStartPostponedTransition(mMemberIconIv);

        if (!TextUtils.isEmpty(mIsszmbalv3MemberInfo.memberCardNo)) {
            getPicDesc(mIsszmbalv3MemberInfo.memberCardNo, mMemberIconIv);
            TextView titleTv = new TextView(this);
            titleTv.setTextColor(ContextCompat.getColor(this, R.color.black));
            titleTv.setTextSize(20);
            titleTv.setGravity(Gravity.CENTER);
            titleTv.getPaint().setFakeBoldText(true);
            Toolbar.LayoutParams layoutParams = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
            titleTv.setLayoutParams(layoutParams);
            String path = mSavePictureDirPath + BarApplication.mStoreName + "_" + "memberId_" + mIsszmbalv3MemberInfo.memberCardNo + ".jpg";
            try {
                File f = new File(path);
                if (!f.exists()) {
                    if(!TextUtils.isEmpty(mIsszmbalv3MemberInfo.memberName.trim())){
                        titleTv.setText(mIsszmbalv3MemberInfo.memberName.trim());
                    }else{
                        titleTv.setText("会员详情");
                    }
                    toolBar.addView(titleTv);
                    coordinatorLayout.setCollapsedTitleTextColor(Color.parseColor("#ff000000"));
                    coordinatorLayout.setExpandedTitleColor(Color.parseColor("#00000000"));
                } else {
                    coordinatorLayout.setCollapsedTitleTextColor(Color.parseColor("#ffffffff"));
                    coordinatorLayout.setExpandedTitleColor(Color.parseColor("#00ffffff"));
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        if(!TextUtils.isEmpty(mIsszmbalv3MemberInfo.memberName)){
            coordinatorLayout.setTitle(mIsszmbalv3MemberInfo.memberName);
        }else{
            coordinatorLayout.setTitle("会员详情");
        }

        Bundle bundle = new Bundle();
        bundle.putBoolean("IsInsertData", mbIsInsertData);
        bundle.putSerializable("Isszmbalv3MemberInfo", mIsszmbalv3MemberInfo);
        mIsszmbalv3MemberEditFragment = new Isszmbalv3MemberEditFragment();
        mIsszmbalv3MemberEditFragment.setArguments(bundle);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.content_frame, mIsszmbalv3MemberEditFragment);
        transaction.commit();

        mIsszmbalv3MemberEditFragment.setOnProcessListener(new Isszmbalv3MemberEditFragment.OnProcessListener() {
            @Override
            public void onProcessFinish(String memberCardNo) {
                if (mPicDescPath != null && mPicDescPath.length() != 0) {
                    new SubmitIsszmbalv3MemberInfoPicDesc().execute(memberCardNo);
                }
            }
        });

        //getWindow().setEnterTransition(initContentEnterTransition());
    }

//    private Transition initContentEnterTransition() {
//        Transition transition= TransitionInflater.from(this).inflateTransition(R.transition.window_detail_enter_transition);
//        transition.addListener(new Transition.TransitionListener() {
//            @Override
//            public void onTransitionStart(Transition transition) {
//
//            }
//
//            @Override
//            public void onTransitionEnd(Transition transition) {
//                transition.removeListener(this);
//            }
//
//            @Override
//            public void onTransitionCancel(Transition transition) {
//
//            }
//
//            @Override
//            public void onTransitionPause(Transition transition) {
//
//            }
//
//            @Override
//            public void onTransitionResume(Transition transition) {
//
//            }
//        });
//        return transition;
//    }

    public void onClick(View v) {
        mIsszmbalv3MemberEditFragment.onClick(v);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finishAfterTransition();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * @desc
     * @author taoli
     * @time 2017/10/10 0010
     * 0:EXPANDED(展开)   1:COLLAPSED(折叠)   2:INTERNEDIATE(中间)
     */
    private int state = 0;
    private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener = new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            //i>=0  Toolbar全部显示
            if (verticalOffset == 0) {
                //修改状态标记为展开
                if (state != 0) {
                    state = 0;
                    toolBar.setNavigationIcon(R.drawable.ic_back_selector);
                    invalidateOptionsMenu();
                    StatusBarUtil.StatusBarLightMode(Isszmbalv3MemberEditActivity.this, R.color.transparent, false);
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                //修改状态标记为折叠
                if (state != 1) {
                    state = 1;
                    toolBar.setNavigationIcon(R.drawable.ic_back_light_selector);
                    invalidateOptionsMenu();
                    StatusBarUtil.setStatusBarColor(Isszmbalv3MemberEditActivity.this, R.color.transparent, false);
                }
            } else {
                //修改状态标记为中间
                if (state != 2) {
                    state = 2;
                }
            }
        }
    };

    private class SubmitIsszmbalv3MemberInfoPicDesc extends AsyncTask<String, Void, String> {
        public SubmitIsszmbalv3MemberInfoPicDesc() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            final String memberCardNoEtStr = params[0].trim();
            if (mPicDescPath != null && mPicDescPath.length() != 0) {
                String picPath = mPicDescPath;
                final File file = new File(picPath);
                if (file.exists()) {
                    final Auth auth = Auth.create(BarApplication.Qiniu_AccessKey, BarApplication.Qiniu_SecretKey);
                    String entry = BarApplication.Qiniu_Bucket + ":" +  BarApplication.mStoreName + "_" + "memberId_" + memberCardNoEtStr + ".jpg";
                    String encodedEntryURI = "http://rs.qiniu.com/delete/" + UrlSafeBase64.encodeToString(entry);
                    String accessToken = auth.signRequest(encodedEntryURI, null, "application/x-www-form-urlencoded");
                    String authorization = "QBox " + accessToken;
                    NetHelper.deleteQiniuRes(Isszmbalv3MemberEditActivity.this, encodedEntryURI, "rs.qiniu.com", "application/x-www-form-urlencoded", authorization, new NetCallback<ServiceResult>() {
                        @Override
                        public void onSucceed(final int code) {
                            uploadPicture(memberCardNoEtStr, auth, file);
                        }

                        @Override
                        public void onSucceed(ServiceResult rspData) {
                            uploadPicture(memberCardNoEtStr, auth, file);
                        }

                        @Override
                        public void onFailed(String msg) {

                        }
                    }, QiniuControl.class);
                }
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    private void uploadPicture(String memberCardNoEtStr, Auth auth, File file){
        String key =  BarApplication.mStoreName + "_" + "memberId_" + memberCardNoEtStr + ".jpg";
        String token = auth.uploadToken(BarApplication.Qiniu_Bucket);
        UploadManager uploadManager = new UploadManager(qiniuConfig);
        uploadManager.put(file, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, final ResponseInfo info, JSONObject res) {
                if (info.isOK()) {
                    Isszmbalv3MemberEditActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Isszmbalv3MemberEditActivity.this, "图片提交成功！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Isszmbalv3MemberEditActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Isszmbalv3MemberEditActivity.this, "图片提交失败，" + info.error, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }, new UploadOptions(null, null, false, new UpProgressHandler() {
            public void progress(String key, double percent) {
            }
        }, null));
    }

    private void getPicDesc(String memberCardNo, final ImageView iv) {
        //String url = BarApplication.Qiniu_BaseDownloadHost + BarApplication.mStoreName + "_" + "memberId_" + memberCardNo + ".jpg";
        //GlideUtils.LoadImage(getActivity(), url, iv);
        String path = "file://" + mSavePictureDirPath + BarApplication.mStoreName + "_" + "memberId_" + memberCardNo + ".jpg";
        Glide.with(getActivity()).load(path).thumbnail(0.1f).into(iv);
    }

    private void pickPicDescImage() {
        if (mPickImageDialog == null) {
            mPickImageDialog = new PickImageDialog(this);
            mPickImageDialog.setItemClickListener(new PickImageDialog.OnItemClick() {
                @Override
                public void onItemClick(int position) {
                    if (position == 0) {
                        //单选打开相册 带配置
                        mPhotoUtils.selectPicture(Isszmbalv3MemberEditActivity.this);
                    } else if (position == 1) {
                        //使用拍照 带配置
                        mPhotoUtils.takePicture(Isszmbalv3MemberEditActivity.this);
                    }
                }
            });
            mPickImageDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                }
            });
            Window window = mPickImageDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.dialog_bottom_anim_style);
        }
        mPickImageDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PhotoUtils.INTENT_CROP:
            case PhotoUtils.INTENT_TAKE:
            case PhotoUtils.INTENT_SELECT:
                mPhotoUtils.onActivityResult(Isszmbalv3MemberEditActivity.this, requestCode, resultCode, data);
                break;
        }
    }
}